<template>
    <div>
      <Breadcrumb title1="用户管理" title2="用户列表"/>
      <div class="container">
        <el-card class="box-card">
          <!-- 搜索 -->
          <el-row :gutter="10" class="search-row">
            <el-col :span="6">
              <el-input v-model="info.query" placeholder="请输入内容" clearable @clear="getUsersListInfo">
                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
              </el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="dialogVisible = true">+新增用户</el-button>
            </el-col>
          </el-row>
          <!-- 用户列表 -->
          <el-table
            :data="usersList"
            style="width: 100%"
            border
            header-align="center"
          >
            <el-table-column align="center" label="ID" width="50" type="index"></el-table-column>
            <el-table-column
              label="姓名"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="邮箱"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.email }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="电话"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.mobile }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="角色"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.role_name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="状态"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                <el-switch
                  style="display: block"
                  v-model="scope.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleSwitchChange(scope.row.id, scope.row.mg_state)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="EditUser(scope.row.id)">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteUserById(scope.row.id)">删除</el-button>
                <el-button size="mini" type="warning" @click="editUsersRole(scope.row)">分配角色</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="pagination flexCenter">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="this.info.pagenum"
            :page-sizes="[1, 2, 3, 4, 5]"
            :page-size="this.info.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.info.total"
            background
          >
          </el-pagination>
          </div>
        </el-card>
      </div>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="40%"
        @close="dialogColse"
      >
        <el-form :model="ruleForm" status-icon :rules="rules" ref="rulesFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="ruleForm.mobile" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="EditdialogVisible"
        width="40%"
        @close="dialogColse"
      >
        <el-form :model="userInfo" status-icon :rules="rules" ref="rulesFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username" disabled/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userInfo.mobile" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="EditdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSumbit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="assignmentVisible"
        width="40%"
        @close="dialogColse"
      >
        <el-form :model="userInfo" status-icon :rules="rules" ref="rulesFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="当前用户名:">{{ userInfo.username }}</el-form-item>
          <el-form-item label="当前用户角色:">{{ userInfo.role_name }}</el-form-item>
          <el-form-item label="分配新角色:">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @change="handleSelectChange(value)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignmentVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSumbit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'
import { validEmail } from '@/utils/validate'
import { getUserList, changeUserStatus, addUser, getUserInfo, editUser, deleteUser } from '@/api/user'
import { editUserRole } from '@/api/roles'
export default {
  name: 'UserList',
  components: {
    Breadcrumb
  },
  data () {
    // 验证邮箱
    const checkEmail = (rules, value, callback) => {
      if (value) {
        if (!validEmail(value)) {
          callback(new Error('请输入正确的邮箱格式'))
        }
        callback()
      }
    }
    // 验证手机号
    const checkMobile = (rule, value, callback) => {
      if (value) {
        if (!/^1[34578]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号格式'))
        }
        callback()
      }
    }
    return {
      info: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      userInfo: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      usersList: [],
      dialogVisible: false,
      EditdialogVisible: false,
      assignmentVisible: false,
      value: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '请输入正确的手机号格式', trigger: 'blur' }
        ]
      },
      options: [{
        value: '1',
        label: '超级管理员'
      }, {
        value: '2',
        label: '测试角色'
      }, {
        value: '3',
        label: '主管'
      }, {
        value: '4',
        label: '普通用户'
      }]
    }
  },
  created () {
    this.getUsersListInfo()
  },
  methods: {
    async getUsersListInfo () {
      try {
        const { data } = await getUserList(this.info)
        this.info.total = data.total
        this.info.pagenum = data.pagenum
        this.usersList = data.users
      } catch (error) {
        console.log(error)
      }
    },
    // 切换分页
    handleSizeChange (size) {
      this.info.pagesize = size
      this.getUsersListInfo()
      console.log(this.info.pagesize)
    },
    // 切换页码
    handleCurrentChange (currentPage) {
      this.info.pagenum = currentPage
      this.getUsersListInfo()
      console.log(this.info.pagenum)
    },
    // 切换开关
    async handleSwitchChange (id, status) {
      try {
        const { meta } = await changeUserStatus(id, status)
        if (meta.status !== 200) {
          this.usersList.find(item => item.id === id).mg_state = !status
          this.$message.success('更新状态失败')
        }
        this.$message.success('更新状态成功')
        this.getUsersListInfo()
      } catch (error) {
        console.log(error)
      }
    },
    // 搜索
    search () {
      if (this.info.query === '') {
        this.$message.error('请输入搜索内容')
        return false
      }
      this.getUsersListInfo(this.info.query)
    },
    // 关闭表单是重置表单
    dialogColse () {
      this.$refs.rulesFormRef.resetFields()
    },
    // 新增用户
    addUsers () {
      this.$refs.rulesFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('创建失败，请检查输入内容！')
          return false
        }
        try {
          await addUser(this.ruleForm)
          this.$message.success('创建成功')
          this.getUsersListInfo()
          this.dialogVisible = false
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 获取用户信息
    async EditUser (id) {
      try {
        const { data } = await getUserInfo(id)
        this.EditdialogVisible = true
        this.userInfo.id = data.id
        this.userInfo.username = data.username
        this.userInfo.email = data.email
        this.userInfo.mobile = data.mobile
      } catch (error) {
        console.log(error)
      }
    },
    // 更新用户信息
    editSumbit () {
      this.$refs.rulesFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('编辑失败，请检查输入内容！')
          this.EditdialogVisible = false
          return false
        }
        try {
          const data = {
            email: this.userInfo.email,
            mobile: this.userInfo.mobile
          }
          await editUser(this.userInfo.id, data)
          this.$message.success('编辑成功！')
          this.getUsersListInfo()
          this.EditdialogVisible = false
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 删除用户
    deleteUserById (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteUser(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getUsersListInfo()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 设置用户角色
    async editUsersRole () {
      this.assignmentVisible = true
      // try {
      console.log(editUserRole)
      // }
      this.$message.success('设置角色成功')
      // setUserRole
    },
    // 选中值发生改变
    handleSelectChange (value) {
      console.log(value)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}
.search-row {
  padding-bottom: 20px;
}
.pagination {
  padding-top: 20px;
}
</style>
